#!/bin/sh

#
# Copyright 2024  Odin Kroeger
#
# This file is part of SieveManager.
#
# SieveManager is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of
# the License, or (at your option) any later version.
#
# SieveManager is distributed in the hope that it will be useful,
# but WITHOUT ALL WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public
# License along with SieveManager. If not, see
# <https://www.gnu.org/licenses/>.
#

set -Cefu


#
# Globals
#

remote="$1"
readonly remote


#
# Functions
#

# Terminate children and clean up before exiting
atexit() {
	__atexit_retval=$?
	trap '' EXIT HUP INT TERM
	set +e
	kill -s TERM -- $(jobs -p) -$$ 2>/dev/null
	wait
	eval "${atexit-}"
	unset atexit
	return "$__atexit_retval"
}

# Catch a signal, clean up, and re-raise the signal
catch() {
	caught="${1:?}"
	[ "${catch-}" ] || return 0
	atexit
	trap - "$caught"
	kill -s "$caught" "$$"
}


#
# Init
#

# Set up clean-up and signal handling
trap atexit EXIT
for sig in HUP INT TERM
do trap "catch $sig" "$sig"
done
caught=


#
# Main
#

# Collect filenames
sources=
while read -r localref localhash remoteref remotehash
do
	branch="${remoteref##*/}"

	if [ "$(git ls-remote "$remote" "refs/heads/$branch")" ]
	then files="$(git diff --name-only "$remote/$branch" HEAD)"
	else files="$(git diff --name-only HEAD)"
	fi

	for file in $files
	do
		case $file in
		(*.py) sources="$sources $file"
		esac
	done
	readonly sources
done

# Check code
if [ "$sources" ]
then
	if ! git diff -s --exit-code
	then
		catch=
		git stash -q
		atexit="git stash pop -q; ${atexit-}"
		catch=y
		[ "$caught" ] && kill -s "$caught" "$$"
	fi

	make PYLINTARGS=--disable=W0511 sources="${sources# }" lint check
fi

